package cmd

import (
	"bufio"
	"bytes"
	"fmt"
	"os/exec"
	"strings"
)

func Cmd(cmd *exec.Cmd) (bool, string) {
	fmt.Println(cmd.Args)

	var out bytes.Buffer
	var stderr bytes.Buffer
	cmd.Stdout =& out
	cmd.Stderr =& stderr
	err := cmd.Run()
	if err != nil {
		fmt.Println (fmt.Sprint(err) + stderr.String())
		return false, fmt.Sprint(err) + stderr.String()
	}
	fmt.Println("Result：\n"+ out.String())
	/*
		str,err := cmd.Output()
		if err!=nil {
			fmt.Println(err)
			//os.Exit(1)
			return false
		}
		if string(str) != ""{
			fmt.Println(string(str))
		}
	*/
	return true, out.String()
}

/*
 * 根据标记判断命令是否执行成功
 */
func CmdSign(cmd *exec.Cmd, successSign string) bool {
	isOK := false
	fmt.Println(cmd.Args)
	stdout, err := cmd.StdoutPipe()
	cmd.Start()
	// 用bufio来接收其他命令调用的打印信息
	in := bufio.NewScanner(stdout)
	for in.Scan() {
		cmdResult := string(in.Bytes())
		fmt.Println(cmdResult)
		if strings.Index(cmdResult, successSign) >= 0 {
			isOK = true
		}
	}

	if err != nil{
		fmt.Println(err)
	}

	cmd.Wait()
	return isOK
}